﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipes;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using Prism.Navigation.Regions;

namespace CPlatePrintSys.Annotation
{
    /// <summary>
    /// 负责调用已有的转换子进程转换功能将SDB文件转换为dxf文档
    /// </summary>
    public class DxfConverterWrapper
    {
        private static Process _childProcess;
        private static IGlobalConfigService _globalConfigService;

        public static readonly string Pipe_Name = "Sdb2DxfPipe";
        public static readonly string Converter_Folder = "SDBConverter";
        public static readonly string Converter_Name = "SDBConverter.exe";
        public static readonly string Temp_Folder = "SDBConverterTemp";

        static DxfConverterWrapper()
        {
            // 尝试从容器中获取全局配置服务
            try
            {
                _globalConfigService = (IGlobalConfigService)Prism.Ioc.ContainerLocator.Container.Resolve(typeof(IGlobalConfigService));
            }
            catch
            {
                // 如果无法获取服务，将使用默认配置
                _globalConfigService = null;
            }
        }

        /// <summary>
        /// 获取图层颜色配置
        /// </summary>
        /// <returns>图层颜色配置，如果无法获取则返回默认配置</returns>
        private static async Task<LayerColorConfig> GetLayerColorConfigAsync()
        {
            try
            {
                if (_globalConfigService != null)
                {
                    return await _globalConfigService.GetLayerColorConfigAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取图层颜色配置失败: {ex.Message}");
            }

            // 返回默认配置
            return new LayerColorConfig();
        }

        private static async Task StartConversion(string sdbFilePath)
        {
            try
            {
                // 获取当前主程序所在目录
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                string converterFolder = System.IO.Path.Combine(baseDirectory, Converter_Folder);
                // 构造子程序路径
                string converterPath = System.IO.Path.Combine(converterFolder, Converter_Name);

                // 启动子程序
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = converterPath,
                    Arguments = Pipe_Name,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    WorkingDirectory = converterFolder
                };

                _childProcess = Process.Start(startInfo);

                // 使用命名管道通信
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", Pipe_Name, PipeDirection.InOut))
                {
                    await pipeClient.ConnectAsync();

                    // 从全局配置中获取图层颜色配置
                    LayerColorConfig colorCfg = await GetLayerColorConfigAsync();
                    
                    ConvertFileInfo fileInfo = new ConvertFileInfo
                    {
                        LineLayerColor = colorCfg.LineLayerColor,
                        TextLayerColor = colorCfg.TextLayerColor,
                        InfoLayerColor = colorCfg.InfoLayerColor,
                        SrcFilePath = sdbFilePath
                    };
                    
                    byte[] filePathBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileInfo, Formatting.None));
                    await pipeClient.WriteAsync(filePathBytes, 0, filePathBytes.Length);
                    await pipeClient.FlushAsync();

                    // 接收转换结果
                    using (StreamReader reader = new StreamReader(pipeClient))
                    {
                        string result = await reader.ReadLineAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                // 确保子程序关闭
                if (_childProcess != null && !_childProcess.HasExited)
                {
                    _childProcess.Kill();
                    _childProcess.Dispose();
                }
            }
        }


        /// <summary>
        /// 通过子进程进行SDB到dxf数据转换（异步版本）
        /// </summary>
        /// <param name="sdbSrcFilePath">SDB源文件路径</param>
        /// <param name="dxfDestFile">DXF目标文件路径</param>
        /// <returns>转换任务</returns>
        public static async Task ConvertSDB2DxfAsync(string sdbSrcFilePath, string dxfDestFile)
        {
            try
            {
                await StartConversion(sdbSrcFilePath);

                // 获取当前主程序所在目录
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                // 获取当前目录下的 SDBConverterTemp 文件夹
                string tempDirectory = System.IO.Path.Combine(baseDirectory, "SDBConverterTemp");

                // 构造转换后的 DXF 文件路径
                string dxfFileName = Path.GetFileNameWithoutExtension(sdbSrcFilePath) + ".dxf";
                string dxfFilePath = Path.Combine(tempDirectory, dxfFileName);

                // 等待文件生成完成
                int maxWaitTime = 30000; // 最大等待30秒
                int waitInterval = 100; // 每100ms检查一次
                int totalWaitTime = 0;
                
                while (!File.Exists(dxfFilePath) && totalWaitTime < maxWaitTime)
                {
                    await Task.Delay(waitInterval);
                    totalWaitTime += waitInterval;
                }

                if (File.Exists(dxfFilePath))
                {
                    File.Copy(dxfFilePath, dxfDestFile, true);
                }
                else
                {
                    throw new FileNotFoundException($"转换后的DXF文件不存在: {dxfFilePath}");
                }
            }
            catch (Exception ex)
            {
                // 记录错误信息
                System.Diagnostics.Debug.WriteLine($"SDB到DXF转换失败: {ex.Message}");
                throw; // 重新抛出异常，让调用者处理
            }
        }

        /// <summary>
        /// 通过子进程进行SDB到dxf数据转换（同步版本，保持向后兼容）
        /// </summary>
        /// <param name="sdbSrcFilePath">SDB源文件路径</param>
        /// <param name="dxfDestFile">DXF目标文件路径</param>
        public static void ConvertSDB2Dxf(string sdbSrcFilePath, string dxfDestFile)
        {
            try
            {
                // 使用异步方法并等待完成
                ConvertSDB2DxfAsync(sdbSrcFilePath, dxfDestFile).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                // 显示错误信息
                MessageBox.Show($"加载 DXF 文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
